package com.pingan.pastry.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class IdUtil {


    public static String uuId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public Gson build() {
        GsonBuilder builder = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
                System.out.println("context: " + context);
                System.out.println("type: " + type);
                System.out.println("jsonElement: " + jsonElement);
                String[] split = jsonElement.getAsString().split("-");
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                if (split == null || split.length == 0){
                    return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
                }else {
                    try {
                        return sdf.parse(jsonElement.getAsJsonPrimitive().getAsString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        });
        return builder.create();
    }


  /*  public static void main(String[] args) {
        IdUtil idUtil = new IdUtil();
        Gson gson = idUtil.build();
        //Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        System.out.println(new Date().getTime()); //1623169695508
        Student student = new Student("xiao", new Date(), new Date());
        String toJson = gson.toJson(student);
        System.out.println(toJson);
        String str = "{\"name\":\"xiao\",\"now\":\"2021-06-09 12:04:05\",\"birth\":1623169695508}";
        Student stu = gson.fromJson(str, Student.class);
        System.out.println(stu.getName() + "birth: " + stu.getBirth());
    }*/
}
